package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BoardMapper;
import com.indusfo.spc.mapper.FixedDeteMapper;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.BoardService;
import com.indusfo.spc.untlis.DateUtils;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName BoardServiceImpl
 * @Description 看板service
 * @Author louk
 * @Date 2020/1/6 8:47
 * @Version 1.0
 */
@Service
public class BoardServiceImpl implements BoardService {
    private  final static int INTERVAL=5;
    private final static int MONTH=30;
    private final static int HOUR=24;

    @Resource
    BoardMapper boardMapper;

    @Resource
    FixedDeteMapper fixedDeteMapper;
    @Override
    public JSONObject queryFixedDetectionResult(Integer fixedDeteId,Integer dayNumber,String endDate) {
        if(fixedDeteId==null || "".equals(fixedDeteId)){
            return JSONObject.build(JSONObject.ERROR,"未获取到项目信息");
        }
        if(!StringUtils.isNumeric(Integer.toString(fixedDeteId))){
            return JSONObject.build(JSONObject.ERROR,"项目类型错误");
        }
        endDate=DateUtils.dateSplicer("23:59:59");
        String checkParamResult = checkParam(dayNumber, endDate);
        if(!StringUtils.isEmpty(checkParamResult)){
            return JSONObject.build(JSONObject.ERROR,checkParamResult);
        }
        String startDate = DateUtils.changeDateDay(endDate, dayNumber);
        if(StringUtils.isEmpty(startDate)){
            return JSONObject.build(JSONObject.ERROR,"网络错误");
        }
        String addUpPercentOfPass = boardMapper.queryAddUpPercentOfPass(fixedDeteId);
        String nowDayPercentOdPass = boardMapper.queryNowDayPercentOdPass(fixedDeteId);
        List<FixedDeteBoardData> fixedDeteBoardDataList = boardMapper.queryFixedDeteBoardInformation(fixedDeteId,startDate,endDate);
        List<FixedDeteBoardData> rejectFixedDeteDetailList = boardMapper.queryRejectFixedDeteDetailList(fixedDeteId, startDate, endDate);
        FixedDeteBoard fixedDeteBoard=new FixedDeteBoard();
        //累计合格率
        fixedDeteBoard.setAddUpPercentOfPass(addUpPercentOfPass);
        //当天合格率
        fixedDeteBoard.setNowDayPercentOdPass(nowDayPercentOdPass);
        //
        fixedDeteBoard.setFixedDeteBoardDataList(fixedDeteBoardDataList);
        //不合格清单
        fixedDeteBoard.setRejectFixedDeteDetailList(rejectFixedDeteDetailList);
        if(fixedDeteBoard!=null){
            return JSONObject.build(JSONObject.SUCCESS,"查询成功",fixedDeteBoard);
        }
        return JSONObject.build(JSONObject.ERROR,"暂无相关数据",fixedDeteBoard);
    }

    @Override
    public JSONObject queryTubDeviceBoard(Integer deviceId) {
        String deviceImg=boardMapper.queryDeviceImg(deviceId);
        DeviceOee deviceOee = boardMapper.queryDeviceOee(deviceId);
        Map<String,DeviceOee> deviceOeeMap = boardMapper.queryDeviceOeeList(deviceId);
        List<String> monthDateList = DateUtils.queryMonthDateByNow();
        List<DeviceOee> newDeviceOeeList=new ArrayList<>();
        for (String dayDate : monthDateList) {
            DeviceOee newDeviceOee=new DeviceOee();
            newDeviceOee.setCreateDate(dayDate);
            if(deviceOeeMap.containsKey(dayDate)){
                newDeviceOee.setOeeRate(deviceOeeMap.get(dayDate).getOeeRate());
            }else{
                newDeviceOee.setOeeRate("0");
            }
            newDeviceOeeList.add(newDeviceOee);
        }
        DeviceRecord deviceRecord = boardMapper.queryDeviceRecord(deviceId);
        Map<String,DeviceRecord> deviceRecordMap = boardMapper.queryDeviceRecordList(deviceId);
        List<DeviceRecord> newDeviceRecordList=new ArrayList<>();
        for(int i=1;i<=HOUR;i++){
            DeviceRecord newDeciceRecord=new DeviceRecord();
            newDeciceRecord.setCreateDate(Integer.toString(i));
            if(deviceRecordMap.containsKey(Integer.toString(i))){
                newDeciceRecord.setRealiEnergy(deviceRecordMap.get(Integer.toString(i)).getRealiEnergy());
            }else{
                newDeciceRecord.setRealiEnergy("0");
            }
            newDeviceRecordList.add(newDeciceRecord);
        }
        TubOee tubOee=new TubOee();
        tubOee.setDeviceImg(deviceImg);
        //实时oee
        tubOee.setDeviceOee(deviceOee);
        //近30天OEE集合
        tubOee.setDeviceOeeList(newDeviceOeeList);
        //设备能耗
        tubOee.setDeviceRecord(deviceRecord);
        //设备能耗集合
        tubOee.setDeviceRecordList(newDeviceRecordList);
        System.out.println(newDeviceOeeList.size()+"---"+newDeviceRecordList.size());
        if(tubOee==null){
            return JSONObject.build(JSONObject.SUCCESS,"暂无相关信息",tubOee);
        }
        return JSONObject.build(JSONObject.SUCCESS,"查询成功",tubOee);
    }

    /**
     * 总装线工艺数据采集看板
     * @param fixedDeteIds
     * @param show
     * @return
     */
    @Override
    public JSONObject queryProcessDataBoard(Integer[] fixedDeteIds, Integer show, String time) {
        try {
            if(fixedDeteIds == null || fixedDeteIds.length == 0 ) {
                throw new ParamsErrorException("请选择要查看的项目");
            }
            if(show == null || show == 0 ) {
                throw new ParamsErrorException("请选择显示类型");
            }
            if(time == null || ("").equals(time)) {
                throw new ParamsErrorException("请选择开始时间");
            }
            String startTime = startTime(show,time);
            List<ProcessData> processDataList = new ArrayList<>();
            // 调用存储过程
            if(show == 1){
                for(Integer fixedDeteId :fixedDeteIds){
                    ProcessData processData = new ProcessData();
                    List<ProcessDataPart> fixedDeteDetailList= boardMapper.queryProcessDataBoardO(fixedDeteId,startTime);
                    FixedDete f = new FixedDete();
                    f.setFixedDeteId(fixedDeteId);
                    FixedDete fixedDete = fixedDeteMapper.selectByPrimaryKey(f);
                    // 把数据加入对象
                    processData.setData(fixedDeteDetailList);
                    processData.setDeteName(fixedDete.getDeteName());
                    processData.setLowerLimit(fixedDete.getLowerLimit());
                    processData.setMiddleLimit(fixedDete.getMiddleLimit());
                    processData.setUpperLimit(fixedDete.getUpperLimit());
                    processData.setFlag(show);
                    // 加入集合中
                    processDataList.add(processData);
                }
            }else if(show == 7){
                for(Integer fixedDeteId :fixedDeteIds){
                    ProcessData processData = new ProcessData();
                    List<ProcessDataPart> fixedDeteDetailList= boardMapper.queryProcessDataBoardT(fixedDeteId,startTime);
                    FixedDete f = new FixedDete();
                    f.setFixedDeteId(fixedDeteId);
                    FixedDete fixedDete = fixedDeteMapper.selectByPrimaryKey(f);
                    // 把数据加入对象
                    processData.setData(fixedDeteDetailList);
                    processData.setDeteName(fixedDete.getDeteName());
                    processData.setLowerLimit(fixedDete.getLowerLimit());
                    processData.setMiddleLimit(fixedDete.getMiddleLimit());
                    processData.setUpperLimit(fixedDete.getUpperLimit());
                    processData.setFlag(show);
                    // 加入集合中
                    processDataList.add(processData);
                }
            }else{
                for(Integer fixedDeteId :fixedDeteIds){
                    ProcessData processData = new ProcessData();
                    List<ProcessDataPart> fixedDeteDetailList= boardMapper.queryProcessDataBoardS(fixedDeteId,startTime);
                    FixedDete f = new FixedDete();
                    f.setFixedDeteId(fixedDeteId);
                    FixedDete fixedDete = fixedDeteMapper.selectByPrimaryKey(f);
                    // 把数据加入对象
                    processData.setData(fixedDeteDetailList);
                    processData.setDeteName(fixedDete.getDeteName());
                    processData.setLowerLimit(fixedDete.getLowerLimit());
                    processData.setMiddleLimit(fixedDete.getMiddleLimit());
                    processData.setUpperLimit(fixedDete.getUpperLimit());
                    processData.setFlag(show);
                    // 加入集合中
                    processDataList.add(processData);
                }
            }
            return JSONObject.oK("查询成功", processDataList,fixedDeteIds.length);
        } catch (GlobalException e) {  //这里只捕获自定义异常
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryDatahis(Integer deviceId) {

        if(deviceId==null || "".equals(deviceId)){
            return JSONObject.build(JSONObject.ERROR,"未获取到设备信息");
        }
        if(!StringUtils.isNumeric(Integer.toString(deviceId))){
            return JSONObject.build(JSONObject.ERROR,"设备信息错误");
        }
        Datahis datahis = boardMapper.queryDatahis(deviceId);
        if(datahis==null){
            return JSONObject.build(JSONObject.ERROR,"暂无相关数据");
        }
        return JSONObject.oK("查询成功",datahis,datahis.getDeviceId());
    }


    public String startTime (Integer show, String time){
        String s = "";
        SimpleDateFormat ymd=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat hms=new SimpleDateFormat("HH:mm:ss");
        try{
            // 获取当前年月日
            Date nyr = ymd.parse(ymd.format(new Date()));
            // 获取当前时分秒
            Date now = hms.parse(hms.format(new Date()));
            // 转换时分秒
            Date sfm = hms.parse(time);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(nyr);
            if(show == 1){
                if(now.before(sfm)){
                    rightNow.add(Calendar.DAY_OF_YEAR,-show);//日期加 日
                }
                Date dt1=rightNow.getTime();
                s = ymd.format(dt1) +" "+ time;
            }else{
                if(now.before(sfm)){
                    rightNow.add(Calendar.DAY_OF_YEAR,-show);//日期加 日
                }else{
                    rightNow.add(Calendar.DAY_OF_YEAR,-show+1);//日期加 日
                }
                Date dt1=rightNow.getTime();
                s = ymd.format(dt1) +" "+ time;
            }
        } catch (Exception e){
        }
        return s;
    }

    /**
     * 当天
     * @param fixedDeteDetailList
     */
    public List<ProcessDataPart> day(List<ProcessDataPart> fixedDeteDetailList){
        return null;
    }
    public String checkParam(Integer dayNumber,String endDate) {


        if(dayNumber==null || "".equals(dayNumber)){
            return "未获取到天数";
        }
        if(!StringUtils.isNumeric(Integer.toString(dayNumber))){
            return "天数类型错误";
        }
        if(StringUtils.isEmpty(endDate)){
            return "未获取到时间信息";
        }
        boolean validDate = DateUtils.isValidDate(endDate, DateUtils.YYYY_MM_DD_HH_MM_SS);
        if(!validDate){
            return "日期格式错误";
        }
        return null;
    }
}
